package com.system.common.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.system.common.util.Result;
import com.system.common.util.SYS;
import com.system.common.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;


public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的token
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);

        // 先判断token是否为空
        if (StrUtil.isBlank(token)) {
            response.setStatus(401);
            Result result = new Result(401, "未提供token", null);
            response.getWriter().print(JSONUtil.toJsonStr(result));
            return false;
        }

        // 判断token是否有效
        if (!TokenUtil.verify(token)) {
            response.setStatus(401);
            Result result = new Result(401, "token无效或已过期", null);
            response.getWriter().print(JSONUtil.toJsonStr(result));
            return false;
        }

        // 放行
        return true;
    }
}